<template>
	<view >
		<cu-custom bgColor="bg-gradual-blue-light"  :isBack="true" backText="返回" title="个人基本信息"></cu-custom>
		<view style="display: flex;align-items: center;justify-content: center; padding: 30rpx 0rpx;">
			<view @tap="ChooseImage('avatar')" class="cu-avatar round xxl bg-white" :style="[{ backgroundImage:'url(' + photoPath + ')' }]">
				<view class="round text-center text-xs" style="background-color: #F85E64;color: #FFFFFF;width: 150rpx;height: 40rpx;line-height: 40rpx;margin-top: 120rpx;">上传头像</view>
			</view>
			<view @tap="ChooseImage('photo')" class="cu-avatar round margin-left-xl xxl bg-white"  :style="[{ backgroundImage:'url(' + photo + ')' }]">
				<view class="round text-center text-xs" style="background-color: #F85E64;color: #FFFFFF;width: 150rpx;height: 40rpx;line-height: 40rpx;margin-top: 120rpx;">上传真人头像</view>
			</view>
		</view>
		<view >
			<zh-text v-model="formData.fullName" :required="true" type="text" label="姓名" labelAlign="left" inputAlign="right" ></zh-text>
			<zh-text v-model="formData.cardTypeName" :required="true" type="text" label="证件类型" labelAlign="left" inputAlign="right" ></zh-text>
			<zh-text v-model="formData.idcard" :required="true" type="text" label="证件号码" labelAlign="left" inputAlign="right" ></zh-text>
			<zh-input v-model="formData.nikeName" :required="true" type="text" label="昵称" labelAlign="left" inputAlign="right" ></zh-input>
			<zh-text v-model="formData.cellphone" :required="true" type="text" label="手机号码" labelAlign="left" inputAlign="right" :rightButtonFlag="true" :rightButton="{text:'修改',bg:'bg-white',color:'#F85E64',textFlag:true}" @right-button-click="openCellphone" ></zh-text>
			<zh-input v-model="formData.email" type="text" label="邮箱" labelAlign="left" inputAlign="right"  :rightButtonFlag="true" :rightButton="{text:'修改',bg:'bg-white',color:'#F85E64',textFlag:true}"  @right-button-click="openEmail"></zh-input>
			<zh-country
				label="国家/地区"
				labelWidth="200rpx"
				labelAlign="left"
				placeholder="请选择国家/地区"
				justifyContent="space-between"
				ref='countrySelect'
				addressRef="countrySelect"
				:value="formData.country"
				rightIconClass="text-gray"
				@selectChange="countryChange"
			>
			</zh-country>
			<zh-address 
				label="居住地"
				labelWidth="150rpx"
				labelAlign="left"
				placeholder="请选择省市区"
				justifyContent="space-between"
				ref='addressSelect'
				addressRef="addressSelect"
				:value="addressValue"
				rightIconClass="text-gray"
				@addressChange="successSelectAddress"
			>
			</zh-address>
			<zh-input v-model="formData.addressDetail" type="text" labelWidth="200rpx" label="详细地址" labelAlign="left" inputAlign="right" ></zh-input>
			<zh-text  type="text" label="更多" labelAlign="left" @textTap="more" rightIconClass="text-gray cuIcon-right" ></zh-text>
			
		</view>
		<view style="padding: 0 30rpx 0 30rpx;" class="flex flex-direction" >
			<button class="cu-btn shadow margin-tb-sm lg bg-gradual-blue-light"  @tap="saveUser">保存</button>
		</view>
		<u-toast ref="uToast" />
		<uni-popup  ref="changeCellphone"  type="center">
			<view class="bg-white">
				<view style="padding-top: 20rpx;" class="text-center text-lg text-bold">
					<text>修改手机号码</text>
				</view>
				<zh-input type="number" v-model="cellphone"  maxlength="11" placeholder="请输入手机号码" :iconClass="['iconfont','icon-shouji1','text-blue']" ></zh-input>
				<view class="cu-form-group">
					<view class="title">
					<text class="iconfont icon-tupianyanzheng text-blue"></text>
					</view>
					<input type="text"  maxlength="4" name="" v-model="imgCode" placeholder="请输入图片验证码"/>
					<image :src="imgSrc" @click="initCode" mode="" class="img-captcha"></image>
				</view>
				<zh-input  type="number" maxlength="4" v-model="shortMsgCode" :iconClass="['iconfont','icon-shoujiyanzheng','text-blue']" :rightButtonFlag="true" :rightButton="{disabled:!codeClick,text:codeBut,bg:'bg-blue-light'}" @right-button-click="getCode" placeholder="手机验证码" ></zh-input>	
				<view style="padding: 0 30rpx 0 30rpx;" class="text-left" >
					<text class="text-gray text-sm">修改成功后需要使用新手机号码登录</text>
				</view>
				<view style="padding: 0 30rpx 0 30rpx;" class="flex flex-direction bg-white" >
					<button class="cu-btn shadow margin-tb-sm lg bg-gradual-blue-light"  @tap="editCellphone">保存</button>
				</view>
			</view>
		</uni-popup>
		<uni-popup  ref="changeEmail"  type="center">
			<view class="bg-white">
				<view style="padding-top: 20rpx;" class="text-center text-lg text-bold">
					<text>修改邮箱</text>
				</view>
				<zh-input type="text" v-model="email"  maxlength="100" placeholder="请输入邮箱" :iconClass="['iconfont','icon-youxiang','text-blue']" ></zh-input>
				<view class="cu-form-group">
					<view class="title">
					<text class="iconfont icon-tupianyanzheng text-blue"></text>
					</view>
					<input type="text"  maxlength="4" name="" v-model="imgCode" placeholder="请输入图片验证码"/>
					<image :src="imgSrc" @click="initCode" mode="" class="img-captcha"></image>
				</view>
				<view style="padding: 0 30rpx 0 30rpx;" class="flex flex-direction" >
					<button class="cu-btn shadow margin-tb-sm lg bg-gradual-blue-light"  @tap="editEmail">保存</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import store from "@/store"
	import searchCountry from "@/components/search-country/country/search-country.vue"
	import reqConfig from '@/common/config/reqConfig.js'
	import api from '@/api/system/base.js'
	import commonApi from '@/api/system/common.js'
	import util from '@/common/util/util.js'
	export default {
		components: {
			searchCountry
		},
		data() {
			return {
				CustomBar: this.$CustomBar,
				userType:store.state.hh_userType,
				formData: {},
				photoPath: '',
				photo: '',
				showCountryFlag:false,
				addressValue:['330000','330700'],
				userId:store.state.hh_user.userId,
				fullName:store.state.hh_user.fullName,
				cellphone:'',
				imgSrc:"",
				codeBut:"获取验证码",
				codeTimer: "",//验证码定义一个定时器的变量
				codeClick:true,
				shortMsgCode:"",
				imgCode: "",
				loginKey: "",
				email:""
			}
		},
		onLoad() {
			this.getPersonInfo()
		},
		onReady() {
			if(!this.loginKey){
				this.loginKey = util.uuid()
			}
		},
		methods: {
			initCode() {
				const url = reqConfig.baseUrl+"/sso/jycy/getImgCode?loginKey="+this.loginKey+"&time="+new Date().getTime()
				this.imgSrc=url
			},
			// 获取验证码
			getCode(){
				var _that = this
				// 倒计时
				if(_that.codeClick){
					if (!this.$validate.isPhone(_that.cellphone)) {
					  uni.showToast({
					    icon: 'none',
					    title: '请输入正确的手机号',
						duration:2000
					  })
					}else{
						// 发送短信
						const sendData = {};
						sendData.loginKey=this.loginKey;
						sendData.cellphone=this.cellphone;
						sendData.smsSendType= 'editCellphone';
						sendData.imgCode= this.imgCode;
						sendData.orgId= this.orgId;
						sendData.userType= this.userType;
						this.$http.post(api.loginSendMessage, sendData).then(res => {
							uni.showToast({
							  icon: 'none',
							  title: '短信发送成功',
							  duration:2000
							})
							_that.codeClick = false
							// 倒计时开始
							var daojishi = 60
							_that.codeTimer = setInterval(function(){
								_that.codeBut = "重新发送"+daojishi;
								daojishi--
								if(daojishi<=0){
									_that.codeBut = "重新发送"
									_that.codeClick = true
									clearInterval(_that.codeTimer);
								}
							},1000)
						}).catch(error => {
							
						})
						
					}
				}
			},
			openCellphone(){
				this.cellphone = ''
				this.shortMsgCode=''
				this.imgCode=''
				this.$refs.changeCellphone.open()
				this.initCode()
			},
			openEmail(){
				this.email = ''
				this.imgCode=''
				this.$refs.changeEmail.open()
				this.initCode()
			},
			editCellphone(){
				
				if(this.cellphone == ""){
					uni.showToast({
						title: '请输入新手机号码',
						icon: 'none',
						duration:2000
					});
					return ;
				}
				if(this.cellphone==this.formData.cellphone){
					uni.showToast({
						title: '请输入新手机号码与系统中的一致，不能修改',
						icon: 'none',
						duration:2000
					});
					return ;
				}
				if(this.imgCode == ""){
					uni.showToast({
						title: '请输入图片验证码',
						icon: 'none',
						duration:2000
					});
					return ;
				}
				if(this.shortMsgCode == ""){
					uni.showToast({
						title: '请输入短信验证码',
						icon: 'none',
						duration:2000
					});
					return ;
				}
				const data = {}
				data.cellphone = this.cellphone
				data.loginKey = this.loginKey
				data.imgCode = this.imgCode
				data.shortMsgCode = this.shortMsgCode
				data.personId = this.formData.personId
				this.$http.post(api.editCellphone, data).then(res => {
					this.formData.cellphone = this.cellphone
					this.$refs.changeCellphone.close()
					this.$refs.uToast.show({
						title: '更新手机成功',
						// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
						type: 'success', 
						position:'top',
						// 如果不需要图标，请设置为false
						icon: false
					})
				}).catch(error => {
						
				})
			},
			editEmail(){
				if(this.email == ""){
					uni.showToast({
						title: '请输入新邮箱',
						icon: 'none',
						duration:2000
					});
					return ;
				}
				if(this.email==this.formData.email){
					uni.showToast({
						title: '请输入新邮箱与系统中的一致，不能修改',
						icon: 'none',
						duration:2000
					});
					return ;
				}
				if(this.imgCode == ""){
					uni.showToast({
						title: '请输入图片验证码',
						icon: 'none',
						duration:2000
					});
					return ;
				}
				if (!this.$validate.isEmail(this.email)) {
				  uni.showToast({
				    icon: 'none',
				    title: '请输入正确的邮箱',
					duration:2000
				  })
				  return
				}
				const data = {}
				data.email = this.email
				data.loginKey = this.loginKey
				data.imgCode = this.imgCode
				data.personId = this.formData.personId
				this.$http.post(api.editEmail, data).then(res => {
					this.formData.email = this.email
					this.$refs.changeEmail.close()
					this.$refs.uToast.show({
						title: '更新邮箱成功',
						// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
						type: 'success', 
						position:'top',
						// 如果不需要图标，请设置为false
						icon: false
					})
				}).catch(error => {
						
				})
			},
			showCountry(){
				this.showCountryFlag = true
			},
			hideCountryModal(){
				this.showCountryFlag = false
			},
			countryChange(e){
				this.formData.country = e.classname
				this.formData.countryName = e.county
				this.showCountryFlag = false
			},
			successSelectAddress(data){
				if(data){
					this.formData.addressProvinceKey = data.province.value
					this.formData.addressProvinceValue = data.province.label
					if(data.city.label){
						this.formData.addressCityKey = data.city.value
						this.formData.addressCityValue = data.city.label
					}
					if(data.county.label){
						this.formData.addressCountyKey = data.county.value
						this.formData.addressCountyValue = data.county.label
					}
					if(data.town.label){
						this.formData.addressStreetKey = data.town.value
						this.formData.addressStreetValue = data.town.label
					}
				}
			},
			more(){
				const params = {}
				this.$Router.push({ name:'userBaseMore',params:params})
			},
			ChooseImage(type) {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						new Promise((resolve, reject) => {
						    uni.uploadFile({
						        url: reqConfig.jhrsUrl+commonApi.uploadFile, //仅为示例，非真实的接口地址
						        filePath: res.tempFilePaths[0],
						        name: 'file',
						        formData: {
						            'uploaderId': this.userId,
									'uploader':this.fullName,
									'fileClassCode':'20'
						        },
						        success: function (uploadFileRes) {
						    		const fileRes = JSON.parse(uploadFileRes.data)
									resolve(fileRes);
						    		
						    		
						        },
						    	fail:function(error){
									reject(err);
						    		
						    	}
						    })
						}).then(data => {
								console.log(data);
								if(!data){
									uni.showToast({
										icon: 'none',
										title: "上传文件失败",
										duration:2000
									})
									return
								}
								if(data &&data.code!== 0){
									uni.showToast({
										icon: 'none',
										title: data.message,
										duration:2000
									})
									return
								}
								const file = data.result.file
								if(!file.flag){
									uni.showToast({
										icon: 'none',
										title: "上传文件失败",
										duration:2000
									})
									return
								}
								const showId = file.showId
								let url = reqConfig.jhrsUrl+commonApi.showFile+"/"+showId
								console.log(type)
								if(type=='photo'){
									this.photo=url
									this.formData.photo=url
									if(this.photoShowId){
										if(showId!=this.photoShowId){
											this.DelImg(this.photoShowId)
										}
									}
									
									this.formData.photoShowId = showId
								}else{
									this.photoPath=url
									this.formData.photoPath=url
									if(this.avatarShowId){
										if(showId!=this.avatarShowId){
											this.DelImg(this.avatarShowId)
										}
									}
									this.formData.avatarShowId = showId
								}
					
								
							}).catch(err => {
								uni.showToast({
									icon: 'none',
									title: '上传文件失败：'+err.message,
									duration:2000
								})
							})
					}
				});
			},
			DelImg(showId) {
				const data = {};
				data.uploaderId=this.userId
				data.uploader=this.fullName
				this.$jhrsHttp.post(commonApi.delFile+"/"+showId, data).then(res => {
				}).catch(error => {
					
				})
			},
			saveUser(){
				this.$http.post(api.saveUser, this.formData).then(res => {
					this.$refs.uToast.show({
						title: '保存成功',
						// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
						type: 'success', 
						position:'top',
						// 如果不需要图标，请设置为false
						icon: false
					})
				}).catch(error => {
						
				})
			},
			getPersonInfo(){
				const data = {}
				this.$http.post(api.getPersonDetail, data).then(res => {
					if(res.result){
						this.formData = res.result
						if(!res.result.country){
							this.formData.country='cn'
						}
						
						this.photoPath=res.result.photoPath?res.result.photoPath:'https://ewm.rsj.jinhua.gov.cn/jhrs/api/common/file/show/jycy/3babbcdbf12d41ea891693fb58c9bb23'
						this.photo=res.result.photo?res.result.photo:'https://ewm.rsj.jinhua.gov.cn/jhrs/api/common/file/show/jycy/3babbcdbf12d41ea891693fb58c9bb23'
						const addressValue = []
						if(res.result.addressProvinceKey){
							addressValue.push(res.result.addressProvinceKey)
							if(res.result.addressCityKey){
								addressValue.push(res.result.addressCityKey)
								if(res.result.addressCountyKey){
									addressValue.push(res.result.addressCountyKey)
									if(res.result.addressStreetKey){
										addressValue.push(res.result.addressStreetKey)
									}
								}
							}
						}
						if(addressValue.length>0){
							console.log(addressValue)
							this.addressValue = addressValue
						}
					}
				}).catch(error => {
					
				})
			}
		},
		beforeDestroy() {
			if (this.codeTimer) {
			    clearInterval(this.codeTimer); // 在Vue实例销毁前，清除我们的定时器
			}
		}
	}
</script>

<style lang="scss">

.img-captcha{
		width: 200rpx;
		line-height: 70rpx;
		height: 70rpx;
		text-align: center;
		margin: 0;
	}
</style>
